﻿using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Data;

namespace hello_accinv_New_
{
    public partial class ChooseProductForm : Form
    {
        private Database db;
        private bool loadingCateogry;

        public string selectedProductCode;

        public ChooseProductForm()
        {
            InitializeComponent();

            db = new Database();

            LoadCategoryList();
        }

        private void LoadCategoryList()
        {
            loadingCateogry = true;

            DataTable dt = db.Select("Name", "Category", "1 ORDER BY Name ASC");
            List<string> lst = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                lst.Add(dt.Rows[i]["Name"].ToString());
            }
            cmbCategoryList.DataSource = lst;
            cmbCategoryList.SelectedIndex = -1;
            dt.Dispose();

            loadingCateogry = false;
        }

        private void LoadProduct(string category)
        {
            dataGridView.DataSource = db.Select("PCode, Product.Name", "Product INNER JOIN Category ON Product.CategoryID = Category.CategoryID", "Product.Flag = '1' AND Category.Name = '" + category + "'");
            dataGridView.ClearSelection();
        }

        private void dataGridView_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            if (dataGridView.SelectedRows.Count == 1)
            {
                btnOK.Enabled = true;
            }
            else
            {
                btnOK.Enabled = false;
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            selectedProductCode = dataGridView.SelectedRows[0].Cells[0].Value.ToString();
        }

        private void cmbCategoryList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!loadingCateogry && cmbCategoryList.SelectedIndex != -1)
            {
                LoadProduct(cmbCategoryList.SelectedItem.ToString());
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Dispose();
        }

        private void dataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            selectedProductCode = dataGridView.SelectedRows[0].Cells[0].Value.ToString();
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }
    }
}
